package cn.kingshion.stack;

import java.util.Scanner;

public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        String key = "";
        boolean loop = true;
        Scanner in = new Scanner(System.in);

        System.out.println("");

        while (loop){
            System.out.println("list: list打印栈");
            System.out.println("push: push入栈");
            System.out.println("pop: pop出栈");
            System.out.println("exit: 退出程序");
            key = in.next();
            switch (key){
                case "list":{
                    arrayStack.list();
                    break;
                }

                case "push":{
                    System.out.println("请输入入栈的元素：");
                    int value = in.nextInt();
                    arrayStack.push(value);
                    break;
                }
                case "pop":{
                    System.out.println("出栈的元素："+arrayStack.pop());
                    break;
                }
                case "exit":{
                    System.out.println("程序结束。。。");
                    in.close();
                    loop = false;
                    break;
                }
                default:{
                    System.out.println("输入有误，请重新输入：");
                    break;
                }
            }
        }
        System.out.println("程序已经退出、、、");
    }
}

class ArrayStack{
    private int maxSize;
    private int top;
    private int arr[];

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[this.maxSize];
        this.top = -1;
    }

    public boolean isFull(){
        return top == maxSize-1;
    }

    public boolean isEmpty(){
        return top == -1;
    }

    public void push(int value){
        if(isFull()){
            System.out.println("栈满，无法入栈！");
            return;
        }
        top++;
        arr[top] = value;
    }

    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空，无法出栈！");
        }
        int value = arr[top];
        top--;
        return value;
    }

    public void list(){
        if(isEmpty()){
//            throw new RuntimeException("栈空，无法出栈！");
            System.out.println("栈空，无法出栈！");
            return;
        }
        for(int i=top;i>=0;i--){
            System.out.println("arr["+i+"] = "+arr[i]);
        }
    }
}
